﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using uPLibrary.Networking.M2Mqtt;
using System.Text.Json;
using EmgrMvc.Models;
using System.Reflection;

namespace EmgrMvc.BLL
{
    public class MqttTool
    {
        public string mqtt_server = "gzhwedu.cn";
        public int mqtt_port = 1883;
        public string username = "guest";
        public string password = "guest";
        public string clientId = "emgrmvc-002";
        //private readonly MyContext _context;
        static MqttTool _singleTon=null;

        private MqttTool()
        {
            //_context = context;
            clientId = "client-" + Guid.NewGuid().ToString().Substring(0, 8);
        }

        public static MqttTool getSingleton()
        {
            if (_singleTon != null)
                return _singleTon;

            _singleTon = new MqttTool();
            return _singleTon;
        }

        static MqttClient ConnectMQTT(string broker, int port, string clientId, string username, string password)
        {
            MqttClient client = new MqttClient(broker);
            //client.Connect(clientId, username, password);
            client.Connect(clientId);
            if (client.IsConnected)
            {
                Console.WriteLine("Connected to MQTT Broker");
            }
            else
            {
                Console.WriteLine("Failed to connect");
            }
            return client;
        }


        void sendData(MqttClient client, string topic, UInt16[] data)
        {

            byte[] buf = new byte[data.Length * 2]; // { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06};

            for (int i = 0; i < data.Length; i++)
            {
                BitConverter.GetBytes(data[i]).CopyTo(buf, i * 2);
            }

            client.Publish(topic, buf);

        }

        public void WakeupPC(string topic, string mac)
        {
            byte[] message = new byte[6];

            string[] chars = mac.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
            if (chars.Length != 6)
                throw new FormatException();

            //逐个字符变为16进制字节数据
            for (int i = 0; i < 6; i++)
            {
                message[i] = Convert.ToByte(chars[i], 16);
            }


            MqttClient client = ConnectMQTT(mqtt_server, mqtt_port, clientId, username, password);
            //Subscribe(client, topic);
            client.Publish(topic, message);
        }

        public void ACControl(string topic, UInt16[] data)
        {
            MqttClient client = ConnectMQTT(mqtt_server, mqtt_port, clientId, username, password);
            sendData(client, topic, data);
        }

        public void ACControl(string topic, string filename)
        {
            string hostName = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            Console.WriteLine(hostName);
            string content = File.ReadAllText(hostName + filename);
            Console.WriteLine(content);
            var data = JsonSerializer.Deserialize<UInt16[]>(content);
            //string[] numbers = content.Split(',');
            //var q = from n in numbers select UInt16.Parse(n);
            ACControl(topic, data);
        }

        public void ResetSchedule()
        {
            MqttClient client = ConnectMQTT(mqtt_server, mqtt_port, clientId, username, password);
            sendData(client, "schedule/reset", new ushort[] { });
        }

        internal void SwitchOn(string topic)
        {
            MqttClient client = ConnectMQTT(mqtt_server, mqtt_port, clientId, username, password);
            sendData(client, topic, new ushort[] { });

        }

        internal void SwitchOff(string topic)
        {
            MqttClient client = ConnectMQTT(mqtt_server, mqtt_port, clientId, username, password);
            sendData(client, topic, new ushort[] { });
        }
    }
}
